import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/stock_materialcheckitem_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/stock_materialcheckitem.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/stock_materialcheck/stock_materialcheckitem/stock_materialcheckitem_dialog.dart';
import 'package:flutter_admin/pages/odoo/stock_materialcheck/stock_materialcheckitem/stock_materialcheckitem_edit.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';

class StockMaterialcheckitemList extends StatefulWidget {
  StockMaterialcheckitemList({Key? key, required this.stockMaterialcheckitem})
      : super(key: key);

  final StockMaterialcheckitem stockMaterialcheckitem;
  @override
  _StockMaterialcheckitemListState createState() =>
      _StockMaterialcheckitemListState();
}

class _StockMaterialcheckitemListState
    extends State<StockMaterialcheckitemList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  StockMaterialcheckitem stockMaterialcheckitem = StockMaterialcheckitem();
  List<StockMaterialcheckitem> selectedList = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        // DataColumn(label: Text('生产单号')),
        DataColumn(label: Text('库房位置')),
        DataColumn(label: Text('库位信息')),
        DataColumn(label: Text('物料编码')),
        DataColumn(label: Text('物料名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('批次号')),
        DataColumn(label: Text('单位')),
        DataColumn(label: Text('账面数量')),
        DataColumn(label: Text('实际盘点数量')),
        DataColumn(label: Text('盘亏')),
        DataColumn(label: Text('盘盈')),
        DataColumn(label: Text('备注')),
      ],
      getCells: (m) {
        StockMaterialcheckitem stockMaterialcheckitem =
            StockMaterialcheckitem.fromMap(m);
        return [
          // DataCell(Text(stockMaterialcheckitem.productorderno ?? '--')),
          DataCell(Text(stockMaterialcheckitem.locationName ?? '--')),
          DataCell(Text(stockMaterialcheckitem.shelvesName ?? '--')),
          DataCell(Text(stockMaterialcheckitem.productCode ?? '--')),
          DataCell(Text(stockMaterialcheckitem.productName ?? '--')),
          DataCell(Text(stockMaterialcheckitem.productDesc ?? '--')),
          DataCell(Text(stockMaterialcheckitem.batchno ?? '--')),
          DataCell(Text(stockMaterialcheckitem.unit ?? '--')),
          DataCell(Text(stockMaterialcheckitem.planQty ?? '--')),
          DataCell(Text(stockMaterialcheckitem.stockqty ?? '--')),
          DataCell(Text(stockMaterialcheckitem.loss ?? '--')),
          DataCell(Text(stockMaterialcheckitem.profit ?? '--')),
          DataCell(Text(stockMaterialcheckitem.remark ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButton(
          label: "导出",
          onPressed: () => _generateExcel(),
          iconData: Icons.import_export_outlined,
        ),
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text('盘点明细数据'),
      ),
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  Future<dynamic> findAll() async {
    formKey.currentState?.save();
    List<StockMaterialcheckitem> resultList = [];
    stockMaterialcheckitem.toMap();
    ResponseBodyApi responseBodyApi =
        await StockMaterialcheckitemOdooApi.findAll(data: {
      "domainList": stockMaterialcheckitem.toDomainList(),
    });
    if (responseBodyApi.success!) {
      resultList = responseBodyApi.data
          .map<StockMaterialcheckitem>((e) => StockMaterialcheckitem.fromMap(e))
          .toList();
    }
    return resultList;
  }

  _generateExcel() async {
    List<StockMaterialcheckitem> selectedList = await findAll();
    if (selectedList == null) {
      return;
    }
    List<Map> map = [
      // {
      //   'name': 'productorderno',
      //   'label': '生产单号',
      //   'columnWidth': 15.0,
      // },

      {
        'name': 'locationName',
        'label': '库房位置',
        'columnWidth': 19.0,
      },
      {
        'name': 'shelvesName',
        'label': '库位信息',
        'columnWidth': 19.0,
      },
      {
        'name': 'productCode',
        'label': '物料编码',
        'columnWidth': 15.0,
      },
      {
        'name': 'productName',
        'label': '物料名称',
        'columnWidth': 20.0,
      },
      {
        'name': 'productDesc',
        'label': '规格型号',
        'columnWidth': 14.0,
      },
      {
        'name': 'batchno',
        'label': '批次号',
        'columnWidth': 10.0,
      },
      {
        'name': 'unit',
        'label': '单位',
        'columnWidth': 10.0,
      },
      {
        'name': 'planQty',
        'label': '账面数量',
        'columnWidth': 10.0,
      },
      {
        'name': 'stockqty',
        'label': '实际盘点数量',
        'columnWidth': 10.0,
      },
      {
        'name': 'loss',
        'label': '盘亏',
        'columnWidth': 10.0,
      },
      {
        'name': 'profit',
        'label': '盘盈',
        'columnWidth': 10.0,
      },
      {
        'name': 'remark',
        'label': '备注',
        'columnWidth': 10.0,
      },
    ];
    Utils.generateExcel(fileName: "盘点明细", configure: map, data: selectedList);
  }

  _edit(StockMaterialcheckitem? stockMaterialcheckitem) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StockMaterialcheckitemEdit(
          stockMaterialcheckitem: stockMaterialcheckitem,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _reset() {
    stockMaterialcheckitem = StockMaterialcheckitem();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    stockMaterialcheckitem.checkId = widget.stockMaterialcheckitem.checkId;
    ResponseBodyApi responseBodyApi = await StockMaterialcheckitemOdooApi.page(
        data: {
          "page": page,
          "domainList": stockMaterialcheckitem.toDomainList()
        });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<StockMaterialcheckitem> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await StockMaterialcheckitemOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StockMaterialcheckitemDialog(),
      ),
    ).then((v) {
      if (v != null) {
        stockMaterialcheckitem = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StockMaterialcheckitem>(
                (e) => StockMaterialcheckitem.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}
